package com.cd2cd.code_template.configuration.security;

import com.cd2cd.code_template.configuration.security.jwt.JwtProperties;
import com.cd2cd.code_template.configuration.security.jwt.JwtUser;
import com.cd2cd.code_template.util.CommUtils;
import com.cd2cd.code_template.util.ExceptionUtils;
import com.cd2cd.code_template.vo.BaseRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.cd2cd.code_template.configuration.constants.ServiceCode.TOKEN_INVALID;
import static com.cd2cd.code_template.configuration.security.ApplicationSecurity.START_WITH_PERMIT_ALL_URL;

@Slf4j
@Component
public class TokenOncePerRequestFilter extends OncePerRequestFilter {

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    JwtUser jwtUser;

    @Resource
    private MyUserDetailsService myUserDetailsService;

    /**
     *
     * @param request
     * @return
     */
    private boolean notRequiresAuthentication(HttpServletRequest request) {
        String uri = request.getRequestURI();

        for (String s : START_WITH_PERMIT_ALL_URL)
            if (uri.startsWith(s))
                return true;

        return false;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if (!this.notRequiresAuthentication(request)) {

            // 获取请求的token
            String authToken = request.getHeader(jwtProperties.getHeader());
            if (StringUtils.isBlank(authToken)) {
                authToken = request.getParameter("access_token");
            }

            if (StringUtils.isNoneBlank(authToken)) {

                log.info("authToken={}", authToken);
                BaseRes<String> res = new BaseRes<>(TOKEN_INVALID);
                try {
                    // 验证token是否有效
                    String rawJson = jwtUser.getClaimByToken(authToken);

                    log.info("rawJson={}", rawJson);

                    /**
                     * 登录用户信息设置
                     */
                    TokenUser tokenUser = myUserDetailsService.loadUserByUsername(rawJson);
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(tokenUser, null, tokenUser.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);

                } catch (Exception e) { // JWTDecodeException SignatureVerificationException
                    ExceptionUtils.setExceptionMsg(e, res);
                    CommUtils.printObjJson(response, res);
                    return;
                }
            } else {
                log.error("token is null uri={}, url={}", request.getRequestURI(), request.getRequestURL());
            }
        }
        filterChain.doFilter(request, response);
    }
}
